package com.carleasoft.mps.core.enums;

import com.carleasoft.mps.core.jackson.BaseEnumDeserializer;
import com.carleasoft.mps.core.result.ErrorResult;
import com.carleasoft.mps.core.utils.ExceptionUtil;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.SneakyThrows;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @author Alay
 * @date 2021-08-09 19:20
 * @project mps
 * @since
 */
@JsonDeserialize(using = BaseEnumDeserializer.class)
public interface BaseEnum extends Serializable {
    /**
     * 获取码
     *
     * @return
     */
    int getCode();

    /**
     * 获取枚举名称
     *
     * @return
     */
    default String getName() {
        return this.name();
    }

    /**
     * 获取枚举名称
     *
     * @return
     */
    String name();

    /**
     * 根据枚举名称获取枚举对象
     *
     * @param clazz
     * @param name
     * @param <E>
     * @return
     */
    @SneakyThrows
    static <E extends Enum<E> & BaseEnum> E sourceOf(Class<E> clazz, String name) {
        Method valuesMethod = clazz.getMethod("values");
        E[] enumInstanceArr = (E[]) valuesMethod.invoke(null);
        for (E enumInstance : enumInstanceArr) {
            if (Objects.equals(name, enumInstance.name())) {
                return enumInstance;
            }
        }
        throw ExceptionUtil.create(ErrorResult.PARAMETER_ERROR);
    }

    /**
     * 根据编码获取枚举对象
     *
     * @param clazz
     * @param code
     * @param <E>
     * @return
     */
    @SneakyThrows
    static <E extends Enum<E> & BaseEnum> E codeOf(Class<E> clazz, int code) {
        Method valuesMethod = clazz.getMethod("values");
        E[] enumInstanceArr = (E[]) valuesMethod.invoke(null);
        for (E enumInstance : enumInstanceArr) {
            if (code == enumInstance.getCode()) {
                return enumInstance;
            }
        }
        throw ExceptionUtil.create(ErrorResult.PARAMETER_ERROR);
    }

}
